using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class SubcategoryControllerBase : BaseController
	{
		#region Members

        protected ISubcategoryService _subcategoryService;
        protected ICategoryService _categoryService;
        protected IProductService _productService;

        #endregion

        #region Constructors

        public SubcategoryControllerBase(ISubcategoryService subcategoryService, ICategoryService categoryService, IProductService productService)
        {
            _subcategoryService = subcategoryService;
            _categoryService = categoryService;
            _productService = productService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /Subcategory
        // **************************************
		public virtual ActionResult Index()
		{
			IndexSubcategoryViewModel viewModel = new IndexSubcategoryViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<Subcategory> searchList = _subcategoryService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _subcategoryService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from subcategory in searchList     // Row data
                       select new
                       {
                           id = subcategory.Id,                
                           cell = new string[] {
						   
                                subcategory.Name,
								subcategory.Description,
								subcategory.Category != null ? subcategory.Category.IdentityDescription : string.Empty
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _subcategoryService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<Subcategory> _subcategoryList = _subcategoryService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;Category");

            // rows
            foreach (Subcategory subcategory in _subcategoryList)
            {
                List<string> rowData = new List<string>() { subcategory.Name, subcategory.Description, subcategory.Category != null ? subcategory.Category.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Subcategory.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /Subcategory/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            Subcategory subcategory = new Subcategory();
            CreateSubcategoryViewModel viewModel = Mapper.Map<Subcategory, CreateSubcategoryViewModel>(subcategory);
            List<Category> allCategory = _categoryService.FindAll();
            viewModel.CategoryList = allCategory;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateSubcategoryViewModel subcategoryModel)
        {
            if (ModelState.IsValid)
            {
                Subcategory subcategory = new Subcategory();
                AutoMapper.Mapper.Map<CreateSubcategoryViewModel, Subcategory>(subcategoryModel, subcategory);
 

				_subcategoryService.Add(subcategory);

                return RedirectToAction("Edit", new { id = subcategory.Id});
            }
            else
            {
				List<Category> allCategory = _categoryService.FindAll();
				subcategoryModel.CategoryList = allCategory;

                return View(subcategoryModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /Subcategory/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            Subcategory subcategory = _subcategoryService.Find(id);
            EditSubcategoryViewModel viewModel = Mapper.Map<Subcategory, EditSubcategoryViewModel>(subcategory);
            List<Category> allCategory = _categoryService.FindAll();
            viewModel.CategoryList = allCategory;
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditSubcategoryViewModel subcategoryModel)
        {
            if (ModelState.IsValid)
            {
                Subcategory subcategory = _subcategoryService.Find(subcategoryModel.Id);
                AutoMapper.Mapper.Map<EditSubcategoryViewModel, Subcategory>(subcategoryModel, subcategory);
                
				_subcategoryService.Change(subcategory);

                return RedirectToAction("Index");
            }
            else
            {
				List<Category> allCategory = _categoryService.FindAll();
				subcategoryModel.CategoryList = allCategory;

                return View(subcategoryModel);
            }
		}
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadProducts(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			Subcategory currentSubcategory = _subcategoryService.Find(masterId);
            List<Product> list = currentSubcategory.Products.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from product in list     // Row data
                       select new
                       {
                           id = product.Id,                
                           cell = new string[] {
                                product.Name,
								product.Description,
								product.Price.ToString(),
								product.Tax.ToString(),
								product.Prominent? "1" : "0",
								product.Weight.ToString(),
								product.Discount.ToString(),
								product.IsInactive.HasValue && product.IsInactive.Value ? "1" : "0"
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddProducts(int masterId = 0)
        {
            PopUpProductViewModel viewModel = new PopUpProductViewModel();

			viewModel.SubcategoryId = masterId;
			ViewBag.MasterProperty = "Subcategory";
            ViewBag.Name = "AddProducts";

            return PartialView("~/Views/Product/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddProducts(PopUpProductViewModel productModel)
        {
            if (ModelState.IsValid)
            {
                Product products = new Product();
                AutoMapper.Mapper.Map<PopUpProductViewModel, Product>(productModel, products);

				Subcategory subcategory = _subcategoryService.Find(products.Subcategory.Id);
				_subcategoryService.AddProducts(subcategory, products);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				ViewBag.MasterProperty = "Subcategory";
            	ViewBag.Name = "AddProducts";


				return PartialView("~/Views/Product/PopUp.cshtml", productModel);
            }
        }	
		
		public virtual ActionResult EditProducts(int id, int masterId = 0)
        {
			Product product = _productService.Find(id);
            PopUpProductViewModel viewModel = Mapper.Map<Product, PopUpProductViewModel>(product);

			List<Subcategory> allSubcategory = _subcategoryService.FindAll();
			viewModel.SubcategoryId = masterId;
			ViewBag.MasterProperty = "Subcategory";
            ViewBag.Name = "EditProducts";

            return PartialView("~/Views/Product/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditProducts(PopUpProductViewModel productModel)
        {
            if (ModelState.IsValid)
            {
                Product product = _productService.Find(productModel.Id);
                AutoMapper.Mapper.Map<PopUpProductViewModel, Product>(productModel, product);

                _productService.Change(product);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Subcategory> allSubcategory = _subcategoryService.FindAll();
				productModel.SubcategoryList = allSubcategory;
				ViewBag.MasterProperty = "Subcategory";

                return PartialView("~/Views/Product/PopUp.cshtml", productModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteProducts(int id, int masterId = 0)
        {
			Product product = _productService.Find(id);
			Subcategory currentSubcategory = _subcategoryService.Find(masterId);

            _subcategoryService.RemoveProducts(currentSubcategory, product);
        }
			
		public virtual FileContentResult ReportProducts(int masterId = 0)
        {
			Subcategory currentSubcategory = _subcategoryService.Find(masterId);
            IList<Product> _productsList = currentSubcategory.Products.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description;Price;Tax;Prominent;Weight;Discount;IsInactive");

            // rows
            foreach (Product product in _productsList)
            {
                List<string> rowData = new List<string>() { product.Name, product.Description, product.Price.ToString(), product.Tax.ToString(), product.Prominent.ToString(), product.Weight.ToString(), product.Discount.ToString(), product.IsInactive.ToString() };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Products.csv");
        }
		

		#endregion

		#region Details

		// *******************************************
        // URL: /Subcategory/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            Subcategory subcategory = _subcategoryService.Find(id);
            DetailsSubcategoryViewModel viewModel = Mapper.Map<Subcategory, DetailsSubcategoryViewModel>(subcategory);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
